<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布商品 - 校园二手交易平台</title>
    <style>
        /* 保持原有样式不变 */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f8f9fa;
            color: #333;
        }
        .container {
            max-width: 800px;
            margin: 30px auto;
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 6px 20px rgba(0,0,0,0.08);
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eaeaea;
        }
        .header h2 {
            margin: 0;
            color: #2c3e50;
            font-size: 28px;
        }
        .header p {
            color: #7f8c8d;
            margin-top: 8px;
        }
        .form-group {
            margin-bottom: 25px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 15px;
        }
        input[type="text"], input[type="number"], select, textarea {
            width: 100%;
            padding: 14px;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-sizing: border-box;
            font-size: 15px;
            transition: border-color 0.3s;
        }
        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }
        textarea {
            height: 130px;
            resize: vertical;
        }
        .btn-group {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }
        .btn {
            padding: 14px 32px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            text-align: center;
            transition: all 0.3s ease;
        }
        .btn-primary {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            box-shadow: 0 4px 10px rgba(52, 152, 219, 0.3);
        }
        .btn-secondary {
            background: linear-gradient(135deg, #95a5a6, #7f8c8d);
            color: white;
            box-shadow: 0 4px 10px rgba(149, 165, 166, 0.2);
        }
        .btn:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }
        .btn:active {
            transform: translateY(0);
        }
        .image-upload-container {
            margin-bottom: 20px;
            padding: 25px;
            border: 2px dashed #bdc3c7;
            border-radius: 10px;
            text-align: center;
            background-color: #f9f9f9;
            transition: all 0.3s;
            position: relative;
        }
        .image-upload-container:hover {
            border-color: #3498db;
            background-color: #f0f8ff;
        }
        #imageUploadInput {
            display: none;
        }
        #imagePreviewContainer {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-top: 20px;
        }
        .image-preview-item {
            position: relative;
            width: 120px;
            height: 120px;
            border: 1px solid #ddd;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 3px 8px rgba(0,0,0,0.1);
            transition: all 0.3s;
        }
        .image-preview-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.15);
        }
        .image-preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .remove-image-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background-color: rgba(231, 76, 60, 0.9);
            color: white;
            border: none;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            font-size: 14px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            line-height: 1;
            transition: all 0.2s;
        }
        .remove-image-btn:hover {
            transform: scale(1.1);
            background-color: #c0392b;
        }
        .upload-icon {
            font-size: 36px;
            color: #3498db;
            margin-bottom: 15px;
        }
        .upload-text {
            color: #7f8c8d;
            margin: 8px 0;
        }
        .add-image-btn {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 12px 20px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            transition: all 0.3s;
            box-shadow: 0 4px 10px rgba(52, 152, 219, 0.3);
        }
        .add-image-btn:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }
        .add-image-btn:active {
            transform: translateY(0);
        }
        .add-image-btn svg {
            margin-right: 8px;
        }
        .primary-tag {
            position: absolute;
            top: 5px;
            left: 5px;
            background-color: rgba(46, 204, 113, 0.9);
            color: white;
            font-size: 11px;
            padding: 3px 8px;
            border-radius: 12px;
            font-weight: 600;
        }
        .set-primary-btn {
            position: absolute;
            bottom: 5px;
            left: 5px;
            right: 5px;
            background-color: rgba(52, 152, 219, 0.8);
            color: white;
            border: none;
            border-radius: 4px;
            padding: 4px;
            font-size: 11px;
            cursor: pointer;
            display: none;
            transition: all 0.2s;
        }
        .image-preview-item:hover .set-primary-btn {
            display: block;
        }
        .set-primary-btn:hover {
            background-color: #2980b9;
        }
        .remaining-count {
            color: #3498db;
            font-weight: 600;
            margin-top: 10px;
            font-size: 14px;
        }
        .image-section-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 15px;
        }
        .image-section-header h3 {
            margin: 0;
            font-size: 18px;
            color: #2c3e50;
        }
        .instructions {
            background-color: #f8f9fa;
            border-left: 4px solid #3498db;
            padding: 15px;
            border-radius: 0 8px 8px 0;
            margin: 20px 0;
            font-size: 14px;
        }
        .instructions h4 {
            margin-top: 0;
            color: #2c3e50;
        }
        .instructions ul {
            padding-left: 20px;
            margin-bottom: 0;
        }
        .instructions li {
            margin-bottom: 8px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h2>发布新商品</h2>
        <p>请填写商品信息，吸引更多买家</p>
    </div>

    <div class="instructions">
        <h4>发布商品须知：</h4>
        <ul>
            <li>请填写真实有效的商品信息，包括标题、价格和详细描述</li>
            <li>上传清晰、真实的商品图片（最多5张）</li>
            <li>第一张图片将作为商品主图展示在列表中</li>
            <li>商品发布后需等待管理员审核（通常需要1-2个工作日）</li>
        </ul>
    </div>

    <form id="itemForm">
        <div class="form-group">
            <label for="title">商品标题:</label>
            <input type="text" id="title" name="title" required maxlength="100" placeholder="例如：九成新iPhone 12 Pro Max">
        </div>

        <div class="form-group">
            <label for="category">商品分类:</label>
            <select id="category" name="category" required>
                <option value="">请选择分类</option>
                <option value="书籍">书籍教材</option>
                <option value="电子">电子产品</option>
                <option value="服饰鞋帽">服饰鞋帽</option>
                <option value="生活用品">生活用品</option>
                <option value="其他">其他</option>
            </select>
        </div>

        <div class="form-group">
            <label for="price">价格 (元):</label>
            <input type="number" id="price" name="price" step="0.01" min="0" required placeholder="0.00">
        </div>

        <div class="form-group">
            <label for="description">商品描述:</label>
            <textarea id="description" name="description" rows="4" required placeholder="请详细描述商品的新旧程度、功能特点、使用情况等信息..."></textarea>
        </div>

        <div class="form-group">
            <div class="image-section-header">
                <h3>商品图片</h3>
                <span class="remaining-count">最多可上传5张图片</span>
            </div>

            <button type="button" id="addImageBtn" class="add-image-btn">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 5V19M5 12H19" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                添加图片
            </button>

            <div id="imageUploadContainer" class="image-upload-container">
                <div class="upload-icon">&#128247;</div>
                <p class="upload-text">点击上方按钮选择图片</p>
                <p class="upload-text">或拖拽图片到此处上传</p>
                <p class="upload-text">支持 .jpg, .jpeg, .png格式</p>
            </div>
            <input type="file" id="imageUploadInput" accept="image/jpeg, image/png" multiple>
            <div id="imagePreviewContainer"></div>
        </div>

        <div class="btn-group">
            <button type="submit" class="btn btn-primary">发布商品</button>
            <a href="index.html" class="btn btn-secondary">返回首页</a>
        </div>
    </form>
</div>

<script>
    let currentUser = null;
    let selectedFiles = []; // 用于存储用户选择的文件对象
    let primaryImageIndex = 0; // 主图索引

    // 检查登录状态
    function checkLogin() {
        const userData = localStorage.getItem('user');
        if (!userData) {
            alert('请先登录！');
            window.location.href = 'login.html';
            return;
        }
        currentUser = JSON.parse(userData);
    }

    // 提交表单
    document.getElementById('itemForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        if (!currentUser || !currentUser.userId) {
            alert('用户未登录或登录信息已过期，请重新登录后再发布商品。');
            checkLogin();
            return;
        }

        const title = document.getElementById('title').value.trim();
        const category = document.getElementById('category').value;
        const price = document.getElementById('price').value;
        const description = document.getElementById('description').value.trim();

        if (!title || !category || !price || !description) {
            alert('请填写所有必填项！');
            return;
        }
        if (selectedFiles.length === 0) {
            alert('请至少上传一张商品图片。');
            return;
        }
        if (parseFloat(price) <= 0) {
            alert('价格必须大于0。');
            return;
        }

        const formData = new FormData();
        formData.append('title', title);
        formData.append('category', category);
        formData.append('price', parseFloat(price));
        formData.append('description', description);
        formData.append('sellerId', currentUser.userId);
        if (currentUser.studentId) {
            formData.append('studentId', currentUser.studentId);
        } else {
            console.warn("currentUser does not have a studentId property.");
        }
        formData.append('primaryImageIndex', primaryImageIndex);

        // 添加图片文件
        selectedFiles.forEach((file, index) => {
            formData.append('images', file);
        });

        try {
            console.log('发送请求数据:', {
                title,
                category,
                price,
                description,
                sellerId: currentUser.userId,
                primaryImageIndex,
                imageCount: selectedFiles.length
            });

            const response = await fetch('/api/items', {
                method: 'POST',
                body: formData
            });

            if (response.ok) {
                const result = await response.json();
                console.log('商品发布成功:', result);
                alert('商品发布成功！等待管理员审核。');
                window.location.href = 'index.html';
            } else {
                let errorMsg = '服务器错误，请稍后重试。';
                try {
                    const errorData = await response.json();
                    errorMsg = errorData.message || response.statusText;
                } catch (e) {
                    console.error('解析错误响应失败:', e);
                }
                console.error('发布失败:', response.status, errorMsg);
                alert(`发布失败: ${errorMsg}`);
            }
        } catch (error) {
            console.error('发布商品时发生网络错误:', error);
            alert('发布商品时发生网络错误，请检查您的网络连接并重试。');
        }
    });

    // 图片上传相关元素
    const addImageBtn = document.getElementById('addImageBtn');
    const imageUploadContainer = document.getElementById('imageUploadContainer');
    const imageUploadInput = document.getElementById('imageUploadInput');
    const imagePreviewContainer = document.getElementById('imagePreviewContainer');
    const remainingCountEl = document.querySelector('.remaining-count');
    const MAX_IMAGES = 5;

    // 添加图片按钮事件
    addImageBtn.addEventListener('click', function() {
        if (selectedFiles.length < MAX_IMAGES) {
            imageUploadInput.click();
        } else {
            alert(`最多只能上传 ${MAX_IMAGES} 张图片。`);
        }
    });

    // 更新剩余图片数量和交互状态
    function updateRemainingCountAndInteractivity() {
        const remaining = MAX_IMAGES - selectedFiles.length;
        remainingCountEl.textContent = `还可上传 ${remaining} 张图片`;

        if (imageUploadContainer) {
            imageUploadContainer.style.cursor = remaining > 0 ? 'pointer' : 'default';
        }

        if (selectedFiles.length === 0) {
            imageUploadContainer.style.display = 'block';
        } else {
            imageUploadContainer.style.display = 'none';
        }
    }

    // 图片上传容器点击事件
    imageUploadContainer.addEventListener('click', function() {
        if (selectedFiles.length < MAX_IMAGES) {
            imageUploadInput.click();
        }
    });

    // 文件选择变化事件
    imageUploadInput.addEventListener('change', (event) => {
        if (event.target.files.length > 0) {
            handleFiles(event.target.files);
        }
        event.target.value = null;
    });

    // 拖拽事件处理
    imageUploadContainer.addEventListener('dragover', (event) => {
        event.preventDefault();
        if (selectedFiles.length < MAX_IMAGES) {
            imageUploadContainer.style.borderColor = '#3498db';
            imageUploadContainer.style.backgroundColor = '#e8f4ff';
        }
    });

    imageUploadContainer.addEventListener('dragleave', (event) => {
        imageUploadContainer.style.borderColor = '#bdc3c7';
        imageUploadContainer.style.backgroundColor = '#f9f9f9';
    });

    imageUploadContainer.addEventListener('drop', (event) => {
        event.preventDefault();
        imageUploadContainer.style.borderColor = '#bdc3c7';
        imageUploadContainer.style.backgroundColor = '#f9f9f9';

        if (selectedFiles.length < MAX_IMAGES && event.dataTransfer && event.dataTransfer.files.length > 0) {
            handleFiles(event.dataTransfer.files);
        } else if (selectedFiles.length >= MAX_IMAGES) {
            alert(`最多只能上传 ${MAX_IMAGES} 张图片。`);
        }
    });

    // 处理上传的文件
    function handleFiles(files) {
        const newFiles = Array.from(files).filter(file => {
            if (!file.type.startsWith('image/')) {
                alert(`文件 "${file.name}" 不是支持的图片格式 (如 .jpg, .png)。`);
                return false;
            }
            return true;
        });

        if (newFiles.length === 0) return;

        for (const file of newFiles) {
            if (selectedFiles.length >= MAX_IMAGES) {
                alert(`图片数量已达上限 (${MAX_IMAGES}张)。 "${file.name}" 及之后的文件未添加。`);
                break;
            }
            if (!selectedFiles.some(f => f.name === file.name && f.size === file.size && f.lastModified === file.lastModified)) {
                selectedFiles.push(file);
                previewFile(file, selectedFiles.length - 1);
            } else {
                alert(`图片 "${file.name}" 已经添加过了。`);
            }
        }
        updateRemainingCountAndInteractivity();
    }

    // 预览文件
    function previewFile(file, index) {
        const reader = new FileReader();
        reader.onload = (e) => {
            const previewItem = document.createElement('div');
            previewItem.classList.add('image-preview-item');
            previewItem.dataset.index = index;

            const img = document.createElement('img');
            img.src = e.target.result;
            img.alt = `预览：${file.name}`;
            previewItem.appendChild(img);

            // 如果是第一张图片，添加主图标记
            if (index === primaryImageIndex) {
                const primaryTag = document.createElement('div');
                primaryTag.classList.add('primary-tag');
                primaryTag.textContent = '主图';
                previewItem.appendChild(primaryTag);
            }

            // 设置主图按钮
            if (index !== primaryImageIndex) {
                const setPrimaryBtn = document.createElement('button');
                setPrimaryBtn.classList.add('set-primary-btn');
                setPrimaryBtn.textContent = '设为主图';
                setPrimaryBtn.addEventListener('click', (event) => {
                    event.stopPropagation();
                    setPrimaryImage(index);
                });
                previewItem.appendChild(setPrimaryBtn);
            }

            // 移除图片按钮
            const removeBtn = document.createElement('button');
            removeBtn.classList.add('remove-image-btn');
            removeBtn.innerHTML = '&times;';
            removeBtn.setAttribute('aria-label', `移除图片 ${file.name}`);
            removeBtn.addEventListener('click', (event) => {
                event.stopPropagation();
                removeImage(index);
            });
            previewItem.appendChild(removeBtn);

            imagePreviewContainer.appendChild(previewItem);
        };
        reader.onerror = () => {
            console.error(`读取文件 ${file.name} 失败。`);
            alert(`预览图片 "${file.name}" 失败。文件可能已损坏或格式不支持。`);
            selectedFiles = selectedFiles.filter((_, i) => i !== index);
            updateRemainingCountAndInteractivity();
        };
        reader.readAsDataURL(file);
    }

    // 移除图片
    function removeImage(index) {
        // 如果移除的是主图，且还有其他图片，将第一张设为主图
        if (index === primaryImageIndex && selectedFiles.length > 1) {
            primaryImageIndex = 0;
        } else if (index < primaryImageIndex) {
            primaryImageIndex--;
        }

        selectedFiles.splice(index, 1);

        // 重新渲染预览
        imagePreviewContainer.innerHTML = '';
        selectedFiles.forEach((file, i) => {
            previewFile(file, i);
        });

        updateRemainingCountAndInteractivity();
    }

    // 设置主图
    function setPrimaryImage(index) {
        primaryImageIndex = index;

        // 重新渲染预览
        imagePreviewContainer.innerHTML = '';
        selectedFiles.forEach((file, i) => {
            previewFile(file, i);
        });

        alert('主图设置成功！');
    }

    // 页面加载时初始化
    function onPageLoad() {
        checkLogin();
        updateRemainingCountAndInteractivity();
    }

    window.addEventListener('load', onPageLoad);
</script>
</body>
</html>